package com.imooc.spring.jdbc.service;

import com.imooc.spring.jdbc.dao.EmployeeDao;
import com.imooc.spring.jdbc.entity.Employee;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

// @Transactional：声明式事务注解，标记在类上或方法上，表示该类或方法需要事务支持，默认事务传播行为为REQUIRED。
@Service
@Transactional(propagation = Propagation.REQUIRED)
public class EmployeeService {
    @Resource
    private EmployeeDao employeeDao;
    @Resource
    private BatchService batchService;

    public EmployeeDao getEmployeeDao() {
        return employeeDao;
    }

    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    public BatchService getBatchService() {
        return batchService;
    }

    public void setBatchService(BatchService batchService) {
        this.batchService = batchService;
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public Employee findById(int id) {
        return employeeDao.findById(id);
    }

    public void batchImport() {
        for (int i = 1; i < 11; i++) {
            if (i == 3) {
                throw new RuntimeException("模拟异常");
            }
            Employee employee = new Employee();
            employee.setEno(8000 + i);
            employee.setEname("张三" + i);
            employee.setSalary(4000f + i);
            employee.setDname("市场部");
            employee.setHireDate(new Date());
            employeeDao.insert(employee);
        }
    }

    public void startImportJob() {
        // 启动批量导入
        batchService.importJob1();
        if (1==1){
            throw new RuntimeException("测试异常");
        }
        batchService.importJob2();
    }
}
